'use client';
import type { Cuisine } from '@/lib/types';
import { useEffect, useState, useCallback } from 'react';

interface Props {
  // 所有菜系分类
  allCuisines: Cuisine[];
  // 初始排除的菜系分类
  initialExcluded: Cuisine[];
  // 提交筛选的回调函数
  onSubmit: (excluded: Cuisine[]) => void;
}

export default function FilterPanel({ allCuisines, initialExcluded, onSubmit }: Props) {
  // 选中的菜系分类
  const [selected, setSelected] = useState<Set<Cuisine>>(new Set(initialExcluded));

  useEffect(() => {
    // 当 initialExcluded 变化时，更新选中的菜系分类
    setSelected(new Set(initialExcluded));
  }, [initialExcluded]);

  const toggle = useCallback((c: Cuisine) => {
    setSelected((prev) => {
      const next = new Set(prev);
      if (next.has(c)) next.delete(c);
      else next.add(c);
      return next;
    });
  }, []);

  const handleSubmit = useCallback(() => {
    // 提交选中的菜系分类
    onSubmit(Array.from(selected));
  }, [selected, onSubmit]);

  const handleKeyDown = useCallback(
    (e: React.KeyboardEvent, cuisine: Cuisine) => {
      if (e.key === 'Enter' || e.key === ' ') {
        e.preventDefault();
        toggle(cuisine);
      }
    },
    [toggle],
  );

  return (
    <div className="space-y-4" role="form" aria-label="餐厅筛选面板">
      <div className="text-sm text-black/70 dark:text-white/70" id="filter-description">
        选择你不想吃的菜系分类，我们将从剩余范围随机抽取。
      </div>
      <div className="flex flex-wrap gap-3" role="group" aria-describedby="filter-description">
        {allCuisines.map((c) => (
          <label
            key={c}
            className="inline-flex items-center gap-2 text-sm cursor-pointer px-3 py-2 rounded-md hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors duration-150"
            tabIndex={0}
            onKeyDown={(e) => handleKeyDown(e, c)}
            aria-label={`排除 ${c} 菜系，当前状态：${selected.has(c) ? '已选中' : '未选中'}`}
          >
            <input
              type="checkbox"
              checked={selected.has(c)}
              onChange={() => toggle(c)}
              className="cursor-pointer"
              aria-label={`排除 ${c}`}
            />
            <span>{c}</span>
          </label>
        ))}
      </div>
      <div className="pt-2">
        <button
          className="rounded-md bg-foreground text-background px-4 py-2 text-sm font-medium hover:bg-foreground/90 transition-colors duration-200 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-foreground"
          onClick={handleSubmit}
          aria-label="提交筛选条件并开始随机选择"
        >
          好了，开始随机！
        </button>
      </div>
    </div>
  );
}
